module app.controller.admin.CategoryController;

import std.json;
import hunt.framework;
import app.repository.CategoryRepository;
import app.response.ResultMsg;
import app.utils.RespCodeEnun;
import app.model.Category;
import app.middleware.CheckIdValidity;

class CategoryController : Controller
{
    mixin MakeController;

    /**
    * 获取所有分类
    */
    @Action Response list()
    {
        ResultMsg resultMsg = new ResultMsg();
        CategoryRepository categoryRepository = new CategoryRepository();

        try
        {
            auto cates = categoryRepository.findAll();
            JSONValue[] items;
            foreach (cate; cates)
            {
                JSONValue item;
                item["id"] = cate.id;
                item["name"] = cate.name;

                items ~= item;
            }

            resultMsg.code = RespCodeEnun.SUCCESS;
            resultMsg.msg = "success";
            resultMsg.data["data"] = items;
        }
        catch (Exception e)
        {
            this.response.setStatus(500);
            resultMsg.code = RespCodeEnun.ERROR;
            resultMsg.msg = "系统异常";
        }

        return new JsonResponse(resultMsg);
    }

    /**
    * 分类详情
    * @id   int   分类id
    */
    @Middleware(CheckIdValidity.stringof)  // id参数检查中间件
    @Action Response detail(long id)
    {
        CategoryRepository categoryRepository = new CategoryRepository();

        auto cate = categoryRepository.findById(id);
        if (cate is null)
        {
            return new JsonResponse(new ResultMsg(RespCodeEnun.Not_Found, "分类未找到"));
        }

        ResultMsg resultMsg = new ResultMsg();
        JSONValue item;
        item["id"] = cate.id;
        item["name"] = cate.name;

        resultMsg.code = RespCodeEnun.SUCCESS;
        resultMsg.msg = "success";
        resultMsg.data["data"] = item;
        return new JsonResponse(resultMsg);

    }

    /**
    * 添加分类
    */
    @Action Response add()
    {
        import std.stdio;

        // 接收提交过来的json值
        JSONValue addJson = request.json();
        string cateName = addJson["name"].str;

        CategoryRepository categoryRepository = new CategoryRepository();

        // 检查是否已经存在
        Category cate = categoryRepository.finByName(cateName);
        if (cate !is null) // 已存在
        {
            this.response.setStatus(403);
            auto result = new ResultMsg(RespCodeEnun.CATEGORYNAME_USED, "分类已存在");
            return new JsonResponse(result);
        }

        try
        {
            import std.datetime.systime : Clock;

            // 添加分类
            Category c = new Category();
            c.name = cateName;
            c.createdAt = Clock.currTime().toUnixTime();
            c.updatedAt = Clock.currTime().toUnixTime();
            categoryRepository.insert(c);

            auto result = new ResultMsg(RespCodeEnun.SUCCESS, "创建成功");
            return new JsonResponse(result);
        }
        catch (Exception e)
        {
            this.response.setStatus(500);
            auto result = new ResultMsg(RespCodeEnun.ERROR, "系统错误");
            return new JsonResponse(result);
        }

    }

    /**
    * 更新分类
    * @id   int
    */
    @Middleware(CheckIdValidity.stringof)  // id参数检查中间件
    @Action Response edit(long id)
    {
        CategoryRepository categoryRepository = new CategoryRepository();

        // 接收提交过来的json值
        JSONValue editJson = request.json();
        string cateName = editJson["name"].str;

        // 查找操作对象
        Category cate1 = categoryRepository.findById(id);
        if (cate1 is null)
        {
            this.response.setStatus(404);
            auto result = new ResultMsg(RespCodeEnun.Not_Found, "操作对象不存在");
            return new JsonResponse(result);
        }

        // 检查是否重名
        Category cate2 = categoryRepository.finByName(cateName);
        if (cate2 !is null)
        {
            this.response.setStatus(403);
            auto result = new ResultMsg(RespCodeEnun.CATEGORYNAME_USED, "分类名称已存在");
            return new JsonResponse(result);
        }

        // 更新
        import std.datetime.systime : Clock;

        cate1.name = cateName;
        cate1.updatedAt = Clock.currTime().toUnixTime();
        try
        {
            categoryRepository.save(cate1);
            auto result = new ResultMsg(RespCodeEnun.SUCCESS, "更新成功");
            return new JsonResponse(result);
        }
        catch (Exception e)
        {
            this.response.setStatus(500);
            auto result = new ResultMsg(RespCodeEnun.ERROR, "更新失败");
            return new JsonResponse(result);
        }
    }

    /**
    * 删除分类
    * @id   int
    */
    @Middleware(CheckIdValidity.stringof)  // id参数检查中间件
    @Action Response del(long id)
    {
        CategoryRepository categoryRepository = new CategoryRepository();

        // 查找操作对象
        Category cate = categoryRepository.findById(id);
        if (cate is null)
        {
            this.response.setStatus(404);
            return new JsonResponse(new ResultMsg(RespCodeEnun.Not_Found, "操作对象不存在"));
        }

        try
        {
            categoryRepository.remove(cate);
            return new JsonResponse(new ResultMsg(RespCodeEnun.SUCCESS, "操作成功"));
        }
        catch (Exception e)
        {
            this.response.setStatus(500);
            return new JsonResponse(new ResultMsg(RespCodeEnun.ERROR, "操作失败"));
        }
    }
}
